package com.yitiao.simple.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 读取客户端数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        System.out.println("client is [" + ctx.channel().remoteAddress() + "]");
        // 如果是 http 请求  HttpObject 对应其子类 defaultHttpRequest
        if (msg instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest) msg;
            //获取uri, 过滤指定的资源
            URI uri = new URI(httpRequest.uri());
            System.out.println("uri:" + uri);
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求了 favicon.ico, 不做响应");
                return;
            }

            String path = uri.getPath().equals("/") ? "/home" : uri.getPath();
            String htmlString = this.toHtmlString(path + ".html");

            //回复信息给浏览器 [http协议]
            ByteBuf content = Unpooled.copiedBuffer(htmlString, CharsetUtil.UTF_16);

            //构造一个http的相应，即 http response
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            //将构建好 response返回
            ctx.writeAndFlush(response);
        }
    }

    /**
     * 读取本地html文件里的html代码
     *
     * @return
     */
    private String toHtmlString(String path) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL resource = classLoader.getResource("codebook"+path);
        // 获取HTML文件流
        StringBuilder htmlSb = new StringBuilder();
        try {
            FileInputStream fileInputStream = new FileInputStream(resource.getFile());
            BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream, StandardCharsets.UTF_8));
            while (br.ready()) {
                htmlSb.append(br.readLine());
            }
            br.close();
            // 删除临时文件
            //file.delete();
        } catch (IOException e) {
            return "文件不存在";
        }
        // HTML文件字符串
        // 返回经过清洁的html文本
        return htmlSb.toString();
    }
}
